import React, { useCallback, useState } from 'react';
import { Upload, File, X, FolderOpen, Plus, Trash2 } from 'lucide-react';
import { VideoFile } from '@/types/video';
import './styles.less';

interface FileListProps {
  files: VideoFile[];
  onFilesSelected: (files: VideoFile[]) => void;
  className?: string;
}

export const FileList: React.FC<FileListProps> = ({ files, onFilesSelected, className = '' }) => {
  const [isDragging, setIsDragging] = useState(false);

  // 模拟文件选择
  const handleSelectFiles = useCallback(() => {
    // 模拟选择文件，实际项目中会调用Tauri对话框
    const mockFiles: VideoFile[] = [
      {
        id: '1',
        name: 'video1.mp4',
        originalName: 'video1.mp4',
        path: '/path/to/video1.mp4',
        size: 1024 * 1024 * 50, // 50MB
        duration: 3600, // 1小时
        format: 'mp4',
        codec: 'h264',
        resolution: { width: 1920, height: 1080 },
        bitrate: 4000,
        frameRate: 30,
        aspectRatio: '16:9',
        audioTracks: [{ index: 0, codec: 'aac', bitrate: 128, sampleRate: 44100, channels: 2 }],
        subtitles: [],
        metadata: { tags: [] },
        createdAt: new Date(),
        updatedAt: new Date(),
      },
      {
        id: '2',
        name: 'video2.mov',
        originalName: 'video2.mov',
        path: '/path/to/video2.mov',
        size: 1024 * 1024 * 100, // 100MB
        duration: 7200, // 2小时
        format: 'mov',
        codec: 'h265',
        resolution: { width: 3840, height: 2160 },
        bitrate: 8000,
        frameRate: 60,
        aspectRatio: '16:9',
        audioTracks: [{ index: 0, codec: 'aac', bitrate: 192, sampleRate: 48000, channels: 2 }],
        subtitles: [],
        metadata: { tags: [] },
        createdAt: new Date(),
        updatedAt: new Date(),
      },
    ];

    onFilesSelected([...files, ...mockFiles]);
  }, [files, onFilesSelected]);

  // 拖拽处理
  const handleDragEnter = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(true);
  }, []);

  const handleDragLeave = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);
  }, []);

  const handleDragOver = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
  }, []);

  const handleDrop = useCallback((e: React.DragEvent) => {
    e.preventDefault();
    e.stopPropagation();
    setIsDragging(false);

    // 在实际项目中，这里会处理拖拽的文件
    console.log('Files dropped:', e.dataTransfer.files);
  }, []);

  // 移除文件
  const handleRemoveFile = useCallback(
    (fileId: string) => {
      onFilesSelected(files.filter(file => file.id !== fileId));
    },
    [files, onFilesSelected]
  );

  // 清空文件列表
  const handleClearAll = useCallback(() => {
    onFilesSelected([]);
  }, [onFilesSelected]);

  const formatFileSize = (bytes: number): string => {
    if (bytes === 0) return '0 B';

    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));

    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const formatDuration = (seconds: number): string => {
    const hours = Math.floor(seconds / 3600);
    const minutes = Math.floor((seconds % 3600) / 60);
    const secs = Math.floor(seconds % 60);

    if (hours > 0) {
      return `${hours}:${minutes.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`;
    } else {
      return `${minutes}:${secs.toString().padStart(2, '0')}`;
    }
  };

  return (
    <div className={`file-list ${className}`}>
      <div className='file-list__header'>
        <h3 className='file-list__title'>文件列表</h3>
        <div className='file-list__controls'>
          {files.length > 0 && (
            <button
              onClick={handleClearAll}
              className='btn btn-outline btn-sm flex items-center space-x-1'
            >
              <Trash2 className='w-4 h-4' />
              <span>清空</span>
            </button>
          )}
          <button
            onClick={handleSelectFiles}
            className='btn btn-primary btn-sm flex items-center space-x-1'
          >
            <Plus className='w-4 h-4' />
            <span>添加文件</span>
          </button>
        </div>
      </div>

      {/* 拖拽区域 */}
      {files.length === 0 ? (
        <div
          className={`file-list__dropzone ${
            isDragging ? 'file-list__dropzone--dragging' : 'file-list__dropzone--idle'
          }`}
          onDragEnter={handleDragEnter}
          onDragLeave={handleDragLeave}
          onDragOver={handleDragOver}
          onDrop={handleDrop}
        >
          <Upload className='file-list__dropzone-icon' />
          <h4 className='file-list__dropzone-title'>拖拽文件到此处</h4>
          <p className='file-list__dropzone-description'>支持 MP4, AVI, MOV, MKV 等视频格式</p>
          <button
            onClick={handleSelectFiles}
            className='btn btn-primary flex items-center space-x-2 mx-auto'
          >
            <FolderOpen className='w-4 h-4' />
            <span>选择文件</span>
          </button>
        </div>
      ) : (
        <div className='file-list__container'>
          <div className='file-list__items'>
            {files.map(file => (
              <div
                key={file.id}
                className='file-list__item'
              >
                <div className='file-list__item-info'>
                  <File className='file-list__item-icon' />

                  <div className='file-list__item-content'>
                    <div className='file-list__item-header'>
                      <span className='file-list__item-name'>{file.name}</span>
                      <span className='file-list__item-format'>
                        {file.format.toUpperCase()}
                      </span>
                    </div>

                    <div className='file-list__item-details'>
                      <span>{formatFileSize(file.size)}</span>
                      <span>{formatDuration(file.duration)}</span>
                      <span>
                        {file.resolution.width}x{file.resolution.height}
                      </span>
                      <span>{file.frameRate} FPS</span>
                    </div>
                  </div>
                </div>

                <button
                  onClick={() => handleRemoveFile(file.id)}
                  className='file-list__item-remove'
                  title='移除文件'
                >
                  <X className='w-4 h-4' />
                </button>
              </div>
            ))}
          </div>

          <div className='file-list__footer'>
            <span className='file-list__count'>共 {files.length} 个文件</span>

            <button
              onClick={handleSelectFiles}
              className='file-list__add-more'
            >
              <Plus className='w-4 h-4' />
              <span>添加更多</span>
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

export default FileList;
